import { _decorator, Component, Node, Label, Canvas, UITransform, Widget, director, Scene, Color, Director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GlobalUserIDManager')
export class GlobalUserIDManager extends Component {
    private static instance: GlobalUserIDManager;
    private userIdLabel: Label = null;
    private userIdNode: Node = null;
    private currentUserId: string = "未知";

    protected onLoad(): void {
        // 确保只有一个实例
        if (GlobalUserIDManager.instance) {
            this.node.destroy();
            return;
        }
        GlobalUserIDManager.instance = this;
        
        // 设置为常驻节点，跨场景不销毁
        director.addPersistRootNode(this.node);
        
        // 创建用户ID显示标签
        this.createUserIDLabel();
        
        // 监听场景切换事件
        director.on(Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this);
    }

    protected onDestroy(): void {
        if (GlobalUserIDManager.instance === this) {
            GlobalUserIDManager.instance = null;
        }
        director.off(Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this);
    }

    public static getInstance(): GlobalUserIDManager {
        return GlobalUserIDManager.instance;
    }

    /**
     * 获取当前场景的Canvas
     */
    private getCanvas(): Canvas | null {
        const currentScene = director.getScene();
        if (currentScene) {
            return currentScene.getComponentInChildren(Canvas);
        }
        return null;
    }

    /**
     * 创建用户ID显示标签
     */
    private createUserIDLabel(): void {
        // 查找当前场景的Canvas
        const canvas = this.getCanvas();
        if (!canvas) {
            console.error('GlobalUserIDManager: 未找到Canvas，无法创建用户ID标签');
            return;
        }

        // 创建用户ID节点
        this.userIdNode = new Node('UserIDLabel');
        
        // 添加到Canvas下而不是当前节点下
        canvas.node.addChild(this.userIdNode);

        // 添加UITransform组件
        const uiTransform = this.userIdNode.addComponent(UITransform);
        uiTransform.setContentSize(300, 40);

        // 添加Label组件
        this.userIdLabel = this.userIdNode.addComponent(Label);
        this.userIdLabel.string = `ID: ${this.currentUserId}`;
        this.userIdLabel.fontSize = 24;
        this.userIdLabel.color = new Color(255, 255, 255, 255); // 白色文字

        // 添加Widget组件用于自动布局
        const widget = this.userIdNode.addComponent(Widget);
        widget.isAlignBottom = true;
        widget.isAlignHorizontalCenter = true;
        widget.bottom = 20; // 距离底部20像素
        widget.alignMode = Widget.AlignMode.ON_WINDOW_RESIZE;

        console.log('GlobalUserIDManager: 用户ID标签已创建并添加到Canvas');
    }

    /**
     * 场景切换时调用
     */
    private onSceneChanged(): void {
        this.ensureLabelVisibility();
    }

    /**
     * 确保标签在新场景中可见
     */
    private ensureLabelVisibility(): void {
        console.log('GlobalUserIDManager: 检查标签可见性...');
        
        // 如果标签节点不存在或已被销毁，重新创建
        if (!this.userIdNode || !this.userIdNode.isValid) {
            console.log('GlobalUserIDManager: 标签节点不存在，重新创建...');
            this.createUserIDLabel();
            return;
        }

        // 确保标签节点在正确的Canvas下
        const canvas = this.getCanvas();
        if (canvas && this.userIdNode.parent !== canvas.node) {
            console.log('GlobalUserIDManager: 将标签移动到新场景的Canvas下...');
            this.userIdNode.removeFromParent();
            canvas.node.addChild(this.userIdNode);
            
            // 重新应用Widget布局
            const widget = this.userIdNode.getComponent(Widget);
            if (widget) {
                widget.updateAlignment();
            }
        }

        // 确保节点是激活状态
        if (this.userIdNode && !this.userIdNode.active) {
            this.userIdNode.active = true;
        }

        console.log('GlobalUserIDManager: 标签可见性已确保');
    }

    /**
     * 更新用户ID显示
     * @param userId 用户ID
     */
    public updateUserID(userId: string): void {
        console.log(`GlobalUserIDManager: 收到用户ID更新请求: ${userId}`);
        this.currentUserId = userId;
        
        if (this.userIdLabel && this.userIdNode) {
            this.userIdLabel.string = `ID: ${userId}`;
            console.log(`GlobalUserIDManager: 用户ID已更新为 ${userId}`);
            console.log(`GlobalUserIDManager: 标签节点激活状态: ${this.userIdNode.active}`);
            console.log(`GlobalUserIDManager: 标签节点位置:`, this.userIdNode.getWorldPosition());
        } else {
            console.error(`GlobalUserIDManager: 标签组件不存在 - Label: ${!!this.userIdLabel}, Node: ${!!this.userIdNode}`);
            // 尝试重新创建标签
            this.createUserIDLabel();
            if (this.userIdLabel) {
                this.userIdLabel.string = `ID: ${userId}`;
            }
        }
    }

    /**
     * 显示标签
     */
    public showLabel(): void {
        if (this.userIdNode) {
            this.userIdNode.active = true;
        }
    }

    /**
     * 隐藏标签
     */
    public hideLabel(): void {
        if (this.userIdNode) {
            this.userIdNode.active = false;
        }
    }

    /**
     * 设置标签样式
     * @param fontSize 字体大小
     * @param color 颜色
     */
    public setLabelStyle(fontSize: number = 24, color: Color = new Color(255, 255, 255, 255)): void {
        if (this.userIdLabel) {
            this.userIdLabel.fontSize = fontSize;
            this.userIdLabel.color = color;
        }
    }

    /**
     * 设置标签位置
     * @param bottom 距离底部的距离
     */
    public setLabelPosition(bottom: number = 20): void {
        const widget = this.userIdNode?.getComponent(Widget);
        if (widget) {
            widget.bottom = bottom;
            widget.updateAlignment();
        }
    }
}
